package com.joe.codemother.controller;

import com.joe.codemother.annotation.AuthCheck;
import com.joe.codemother.common.BaseResponse;
import com.joe.codemother.entity.App;
import com.joe.codemother.entity.ChatHistory;
import com.joe.codemother.entity.User;
import com.joe.codemother.entity.dto.ChatHistoryAdminQueryRequest;
import com.joe.codemother.entity.dto.ChatHistoryQueryRequest;
import com.joe.codemother.exception.BusinessException;
import com.joe.codemother.exception.ErrorCode;
import com.joe.codemother.service.AppService;
import com.joe.codemother.service.ChatHistoryService;
import com.joe.codemother.service.UserService;
import com.joe.codemother.util.ResultUtils;
import com.joe.codemother.util.ThrowUtils;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 对话历史 控制层。
 *
 * @author joe
 */
@RestController
@RequestMapping("/chatHistory")
public class ChatHistoryController {

	@Autowired
	private ChatHistoryService chatHistoryService;

	@Autowired
	private UserService userService;

	@Autowired
	private AppService appService;

	/**
	 * 【用户】分页查询某个应用的对话历史（仅创建者可见），每次最新10条，可向前加载。
	 */
	@PostMapping("/my/list/page")
	public BaseResponse<List<ChatHistory>> listMyAppHistories(@RequestBody ChatHistoryQueryRequest queryRequest,
																HttpServletRequest request) {
		ThrowUtils.throwIf(queryRequest == null || queryRequest.getAppId() == null, ErrorCode.PARAMS_ERROR);
		int pageSize = Math.min(Math.max(Objects.requireNonNullElse(queryRequest.getPageSize(), 10), 1), 50);
		User loginUser = userService.getLoginUser(request);
		Long appId = queryRequest.getAppId();
		App app = appService.getById(appId);
		ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR);
		ThrowUtils.throwIf(!Objects.equals(app.getUserId(), loginUser.getId()), ErrorCode.NO_AUTH_ERROR);
		Long lastId = queryRequest.getLastId();
		QueryWrapper wrapper = chatHistoryService.buildUserAppQueryWrapper(appId, loginUser.getId());
		if (lastId != null && lastId > 0) {
			wrapper.lt("id", lastId);
		}
		wrapper.orderBy("id", false).limit(pageSize);
		List<ChatHistory> list = chatHistoryService.list(wrapper);
		return ResultUtils.success(list);
	}

	/**
	 * 【管理员】分页查询所有对话历史，时间倒序。
	 */
	@PostMapping("/admin/list/page")
	@AuthCheck(mustRole = "admin")
	public BaseResponse<Page<ChatHistory>> adminListByPage(@RequestBody ChatHistoryAdminQueryRequest queryRequest) {
		ThrowUtils.throwIf(queryRequest == null, ErrorCode.PARAMS_ERROR);
		int pageNum = Math.max(Objects.requireNonNullElse(queryRequest.getPageNum(), 1), 1);
		int pageSize = Math.max(Objects.requireNonNullElse(queryRequest.getPageSize(), 10), 1);
		Page<ChatHistory> page = chatHistoryService.pageAdmin(pageNum, pageSize, queryRequest.getAppId(), queryRequest.getUserId());
		return ResultUtils.success(page);
	}
}
